package com.ayf.payment.game.api.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.swwx.charm.commons.lang.utils.LogPortal;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class QRCode {
    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;
    private static final int WIDTH = 400; // 二维码宽度
    private static final int HEIGHT = 400;// 二维码高度
    private static final int LOG_WIDTH = 120;// Log宽度
    private static final int LOG_HEIGHT = 60;// Log高度

    private static final String DEFAULT_CHARSET="UTF-8";

    public static void main(String[] args) throws Exception {
        File qrcFile = new File("/Users/syf/Desktop/","134.gif");
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx24e1c575a6bf61ab&redirect_uri=https%3A%2F%2Fwww.paymax.cc%2Fmerchant-api%2Fwechat_pub%2FcreateOrder&response_type=code&scope=snsapi_base&state=ch20200312235953dDThYNfuYj#wechat_redirect";
//        writeToFile(url, "gif", qrcFile);
//        pressText("仅供传奇游戏充值，谨防诈骗", qrcFile, 5, Color.RED, 20);
        writeToFile(url,"gif",qrcFile);
//        createQrCode(null,url,"gif","仅供传奇游戏充值，谨防诈骗");
    }

    /**
     * 把生成的二维码存入到图片中
     * @param matrix zxing包下的二维码类
     * @return
     */
    public static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
            }
        }
        return image;
    }
    /**
     * 生成二维码并写入文件
     * @param content 扫描二维码的内容
     * @param format 图片格式 jpg
     * @param file  文件
     * @throws Exception
     */
//    public static void writeToFile(String content, String format, File file) throws Exception {
//        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
//        @SuppressWarnings("rawtypes")
//        Map hints = new HashMap();
//        //设置UTF-8， 防止中文乱码
//        hints.put(EncodeHintType.CHARACTER_SET, DEFAULT_CHARSET);
//        //设置二维码四周白色区域的大小
//        hints.put(EncodeHintType.MARGIN,1);
//        //设置二维码的容错性
//        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
//        //画二维码
//        BitMatrix bitMatrix = multiFormatWriter.encode(content,BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
//        BufferedImage image = toBufferedImage(bitMatrix);
//
//        // 插入LOG
//        insertImage(image,"/Users/syf/Desktop/zp.png",true);
//        if (!ImageIO.write(image, format, file)) {
//            throw new IOException("Could not write an image of format " + format + " to " + file);
//        }
//    }

    /**
     * 给二维码图片加上文字
     * @param pressText 文字
     * @param qrFile  二维码文件
     * @param fontStyle
     * @param color
     * @param fontSize
     */
    public static void pressText(String pressText, File qrFile, int fontStyle, Color color, int fontSize) throws Exception {
        pressText = new String(pressText.getBytes(), DEFAULT_CHARSET);
        Image src = ImageIO.read(qrFile);
        int imageW = src.getWidth(null);
        int imageH = src.getHeight(null);
        BufferedImage image = new BufferedImage(imageW, imageH, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.createGraphics();
        g.drawImage(src, 0, 0, imageW, imageH, null);
        //设置画笔的颜色
        g.setColor(color);
        //设置字体
        Font font = new Font("宋体", fontStyle, fontSize);
        FontMetrics metrics = g.getFontMetrics(font);
        //文字在图片中的坐标 这里设置在中间
        int startX = (WIDTH - metrics.stringWidth(pressText)) / 2;
        int startY = HEIGHT/2;
        g.setFont(font);
        g.drawString(pressText, startX, startY);
        g.dispose();
        FileOutputStream out = new FileOutputStream(qrFile);
        ImageIO.write(image, "gif", out);
        out.close();
        System.out.println("image press success");
    }


    /**
     *
     * @param source
     * @param logImgInputStream
     * @param needCompress
     * @throws Exception
     */
    private static void insertImage(BufferedImage source,InputStream logImgInputStream, boolean needCompress) throws Exception {
        Image src = ImageIO.read(logImgInputStream);
        int width = src.getWidth(null);
        int height = src.getHeight(null);
        if (needCompress) { // 压缩LOGO
            if (width > LOG_WIDTH) {
                width = LOG_WIDTH;
            }
            if (height > LOG_HEIGHT) {
                height = LOG_HEIGHT;
            }
            Image image = src.getScaledInstance(width, height,Image.SCALE_SMOOTH);
            BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics g = tag.getGraphics();
            g.drawImage(image, 0, 0, null); // 绘制缩小后的图
            g.dispose();
            src = image;
        }
        // 插入LOGO
        Graphics2D graph = source.createGraphics();
        int x = (WIDTH - width) / 2;
        int y = (WIDTH - height) / 2;
        graph.drawImage(src, x, y, width, height, null);
        Shape shape = new RoundRectangle2D.Float(x, y, width, height, 6, 6);
        graph.setStroke(new BasicStroke(1f));
        graph.draw(shape);
        graph.dispose();
    }



    /**
     * 生成二维码并写入文件
     * @param content 扫描二维码的内容
     * @param format 图片格式 jpg
     * @param file  文件
     * @throws Exception
     */
    public static void writeToFile(String content, String format,File file) throws Exception {
        String beginText = new String("仅限传奇游戏充值".getBytes(),DEFAULT_CHARSET);
        String endText = new String("其它勿扫".getBytes(),DEFAULT_CHARSET);
        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        @SuppressWarnings("rawtypes")
        Map hints = new HashMap();
        //设置UTF-8， 防止中文乱码
        hints.put(EncodeHintType.CHARACTER_SET, DEFAULT_CHARSET);
        //设置二维码四周白色区域的大小
        hints.put(EncodeHintType.MARGIN,1);
        //设置二维码的容错性
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        //画二维码
        BitMatrix bitMatrix = multiFormatWriter.encode(content,BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
        BufferedImage image = toBufferedImage(bitMatrix);

        // 插入LOG
        insertImage(image,new FileInputStream("/Users/syf/Downloads/zp.png"),true);

        Graphics g = image.createGraphics();
        g.drawImage(image, 0, 0, image.getWidth(),image.getHeight(), null);
        //设置画笔的颜色
        g.setColor(Color.red);
        //设置字体
        Font font = new Font("宋体", 5, 20);
        FontMetrics metrics = g.getFontMetrics(font);
        //文字在图片中的坐标 这里设置在中间
        int startX = ((WIDTH - metrics.stringWidth(beginText))/2);
        int startY = (HEIGHT/3);
        g.setFont(font);
        g.drawString(beginText,startX,startY);

        g.drawString(endText,((WIDTH-metrics.stringWidth(endText))/2),(HEIGHT-startY));
        g.dispose();

        FileOutputStream out = new FileOutputStream(file);
        ImageIO.write(image,format, out);
        out.close();
        System.out.println("image press success");
    }

    /**
     * 生成二维码文件流
     * @param outputStream
     * @param content 扫描二维码的内容
     * @param imageFormat 图片格式
     * @throws Exception
     */
    public static void createQrCode(OutputStream outputStream,String content,String imageFormat) throws Exception {
        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        @SuppressWarnings("rawtypes")
        Map hints = new HashMap();
        //设置UTF-8， 防止中文乱码
        hints.put(EncodeHintType.CHARACTER_SET,DEFAULT_CHARSET);
        //设置二维码四周白色区域的大小
        hints.put(EncodeHintType.MARGIN,1);
        //设置二维码的容错性
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        //画二维码
        BitMatrix bitMatrix = multiFormatWriter.encode(content,BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
        BufferedImage image2 = toBufferedImage(bitMatrix);

        // 插入LOG
        insertImage(image2, QRCode.class.getClassLoader().getResourceAsStream("zp.png"),true);
//        // 插入文字说明
//        String beginText = new String("仅限传奇游戏充值".getBytes(),DEFAULT_CHARSET);
//        String endText = new String("其它勿扫".getBytes(),DEFAULT_CHARSET);
//        Graphics g = image2.createGraphics();
//        g.drawImage(image2, 0, 0, image2.getWidth(),image2.getHeight(), null);
//        //设置画笔的颜色
//        g.setColor(Color.red);
//        //设置字体
//        Font font = new Font("微软雅黑", Font.BOLD, 30);
//        FontMetrics metrics = g.getFontMetrics(font);
//        //文字在图片中的坐标 这里设置在中间
//        int startX = ((WIDTH - metrics.stringWidth(beginText))/2);
//        int startY = (HEIGHT/3);
//        g.setFont(font);
//        g.drawString(beginText,startX,startY);
//        g.drawString(endText,((WIDTH-metrics.stringWidth(endText))/2),(HEIGHT-startY));
//        g.dispose();

        ImageIO.write(image2,imageFormat,outputStream);
    }
}
